import { Main } from "../Main";
import { ManifestGenUtil } from "./ManifestGenUtil";
import { ShellUtil } from "./ShellUtil";
import { EncryptResUtil } from "./EncryptResUtil";
import { SvnUtil } from "./SvnUtil";
import { ConfigUtil } from "./ConfigUtil";
import { ChangeLuaCodeUtil } from "./ChangeLuaCodeUtil";
import { ProcessResSrcUtil } from "./ProcessResSrcUtil";

/**
 * 热更新包生成工具
 * @author 赵占涛
 */
export class UpdateGenUtil {
    /**
     * 生成热更新包
     * @param plat 平台
     * @param cb 完成回调
     */
    static gen(plat: string, iosOrAndroid: "ios" | "android", cb: () => void) {
        // 生成manifest，
        let path = Main.codePath + "Resources/";
        let gateUrl = ConfigUtil.PlatCfg[plat].updateGateUrl + "debug/" + iosOrAndroid + "/";
        let cdnUrl = ConfigUtil.PlatCfg[plat].updateCdnUrl + "debug/" + iosOrAndroid + "/";
        let projectManifest = path + "project.manifest";
        let versionManifest = path + "version.manifest";

        SvnUtil.getVersion(Main.codePath + "", (version: string) => {
            console.log("版本号是" + version);

            ProcessResSrcUtil.exec(plat, iosOrAndroid, () => {
                ManifestGenUtil.gen(path, gateUrl, cdnUrl, version, projectManifest, versionManifest, (fileMd5) => {
                    console.log("Manifest生成 ok");
                    // 改文件名为带md5的
                    this.renameByMd5(path, fileMd5, () => {
                        console.log("改文件名 ok");
                        ShellUtil.exec(`
    rsync -avz --delete ${path}project.manifest ${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/project.manifest || exit 1
    rsync -avz --delete ${path}version.manifest ${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/version.manifest || exit 1
    rsync -avz --delete ${path}src/ ${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/src/ || exit 1
    rsync -avz --delete ${path}res/ ${Main.projPath}publishclient/${plat}/debug/${iosOrAndroid}/res/ || exit 1
                            `, cb);
                    });
                });
            });
        });
    }
    /** 改名为带md5的 */
    private static renameByMd5(path: string, fileMd5: { [key: string]: { md5: string } }, cb: () => void) {

        // 改文件名为带md5的
        let renameCount = 0;
        let fileCount = Object.keys(fileMd5).length;
        for (const file in fileMd5) {
            if (fileMd5.hasOwnProperty(file)) {
                const md5 = fileMd5[file].md5;
                ShellUtil.exec(`
                    mv ${path}${file} ${path}${file}.${md5} || exit 1
                    `, () => {
                    renameCount++;
                    if (renameCount == fileCount) {
                        cb();
                    }
                });
            }
        }
    }
}